﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace NetMemosBackground
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
            timerAlert.Start();
        }

        /// <summary>  
        /// 获取当前时间戳  
        /// </summary>  
        /// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳.bool bflag = true</param>  
        /// <returns></returns>  
        public static string GetTimeStamp(bool bflag)
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string ret = string.Empty;
            if (bflag)
                ret = Convert.ToInt64(ts.TotalSeconds).ToString();
            else
                ret = Convert.ToInt64(ts.TotalMilliseconds).ToString();
            return ret;
        }

        public void handleQuicknoteAlert() {
            List<ShortNote> lsn = this.getAlarmedNotes();
            foreach (ShortNote sn in lsn)
            {
                if (sn.Salerted == 1)
                {
                    if (long.Parse(sn.SalertTime) <= (long.Parse(GetTimeStamp(false))))
                    {
                        int uid = sn.Suid;
                        string email = getTargetUser(uid).Uemail;
                        send(email,sn.Scontent);
                        unSetAlarm(sn.ID.ToString());
                        listResult.Items.Add("向" + email + "发送了提醒                     " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                    }
                }
            }
            this.lbl_alert.Text =lsn.Count + "";
        }

        public void unSetAlarm(string sid)
        {
            string sql = "update Shortnotes set Salerted=0, SalertTime='' where ID=" + int.Parse(sid);
            OleDB oledb = new OleDB();
            oledb.executeSql(sql);
        }

        public Users getTargetUser(int ID)
        {
            Users u = new Users();
            OleDB oledb = new OleDB();
            var query = oledb.getDataSet("select * from Users where ID=" + ID);

            u.ID = int.Parse(query.Tables[0].Rows[0]["ID"].ToString());
            u.Uname = query.Tables[0].Rows[0]["Uname"].ToString();
            u.Uemail = query.Tables[0].Rows[0]["Uemail"].ToString();
            u.Uphone = query.Tables[0].Rows[0]["Uphone"].ToString();
            u.Upwd = query.Tables[0].Rows[0]["Upwd"].ToString();
            u.Ubirth = query.Tables[0].Rows[0]["Ubirth"].ToString();
            u.Ugender = query.Tables[0].Rows[0]["Ugender"].ToString();
            u.Uface = query.Tables[0].Rows[0]["Uface"].ToString();
            u.Uregdate = query.Tables[0].Rows[0]["Uregdate"].ToString();
            u.Urealname = query.Tables[0].Rows[0]["Urealname"].ToString();
            u.Udesc = query.Tables[0].Rows[0]["Udesc"].ToString();
            u.Uaddress = query.Tables[0].Rows[0]["Uaddress"].ToString();
            u.Uemotion = query.Tables[0].Rows[0]["Uemotion"].ToString();
            u.Ufacebg = query.Tables[0].Rows[0]["Ufacebg"].ToString();
            u.UfollowID = query.Tables[0].Rows[0]["UfollowID"].ToString();
            u.UsuperPwd = query.Tables[0].Rows[0]["UsuperPwd"].ToString();
            u.UbackID = query.Tables[0].Rows[0]["UbackID"].ToString();

            return u;
        }

        public List<ShortNote> getAlarmedNotes()
        {
            string sql = "select * from ShortNotes,Snclass where ShortNotes.Sclass=Snclass.ID and Salerted=1";
            OleDB oledb = new OleDB();
            List<ShortNote> lsn = new List<ShortNote>();
            var query = oledb.getDataSet(sql).Tables[0];
            for (int i = 0; i < query.Rows.Count; i++)
            {
                ShortNote sn = new ShortNote();
                sn.ID = int.Parse(query.Rows[i]["ID"].ToString());
                sn.Scontent = query.Rows[i]["Scontent"].ToString().Replace("‘", "'");
                sn.Stime = query.Rows[i]["Stime"].ToString();
                sn.Scid = int.Parse(query.Rows[i]["Sclass"].ToString());
                sn.Sclass = query.Rows[i]["SNname"].ToString();
                sn.Suid = int.Parse(query.Rows[i]["Suid"].ToString());
                sn.Salerted = int.Parse(query.Rows[i]["Salerted"].ToString());
                sn.SalertTime = query.Rows[i]["SalertTime"].ToString();
                sn.Senable = int.Parse(query.Rows[i]["Senable"].ToString());
                lsn.Add(sn);
            }
            return lsn;
        }

        public int getShortNoteListNum()
        {
            OleDB oledb = new OleDB();
            int count = oledb.getIntegerValue("select count(*) from ShortNotes where Senable=1");           
            return count;
        }

        private void send(string email,string content)
        {
            Outlook.Application olApp = new Outlook.Application();
            Outlook.MailItem mailItem = (Outlook.MailItem)olApp.CreateItem(Outlook.OlItemType.olMailItem);
            mailItem.To =email;
            mailItem.Subject = "来自网事的提醒 "+DateTime.Now.ToString("yyyy-MM-dd hh:mm");
            mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;          

            mailItem.HTMLBody = content;
            try
            {
                ((Outlook._MailItem)mailItem).Send();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                mailItem = null;
                olApp = null;
            }
        }

        private void timerAlert_Tick(object sender, EventArgs e)
        {
            handleQuicknoteAlert();
            this.lbl_num.Text = getShortNoteListNum() + "";
        }
    }

    public class Users
    {
        public Users(){}

        public int ID { get; set; }
        public string Uname { get; set; }
        public string Uemail { get; set; }
        public string Uphone { get; set; }
        public string Upwd { get; set; }
        public string Ubirth { get; set; }
        public string Ugender { get; set; }
        public string Uface { get; set; }
        public string Uregdate { get; set; }
        public string Urealname { get; set; }
        public string Udesc { get; set; }
        public string Uaddress { get; set; }
        public string Uemotion { get; set; }
        public string Ufacebg { get; set; }
        public string UbackID { get; set; }
        public string UfollowID { get; set; }
        public string UsuperPwd { get; set; }
        public string UlastLoginTime { get; set; }
    }

    public class ShortNote
    {
        public ShortNote(){}

        public int ID { get; set; }
        public string Scontent { get; set; }
        public string Stime { get; set; }
        public int Scid { get; set; }
        public string Sclass { get; set; }
        public int Suid { get; set; }
        public int Senable { get; set; }
        public int Salerted { get; set; }
        public string SalertTime { get; set; }
        public int Sheight { get; set; }
    }
}
